<template>
  <a-modal
    :title="title"
    :visible="visible"
    :confirm-loading="loading"
    :width="720"
    @ok="modalOK"
    @cancel="cancelModal"
  >
    <!-- @ok="() => { $emit('cancel') }" -->
    <a-spin :spinning="loading">
      <a-form
        :form="form"
        v-bind="formLayout"
        @submit="formSubmit"
      >
        <!-- <a-form-item v-show="model && model.id > 0" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item> -->
        <a-input
          hidden
          :disabled="update"
          v-decorator="['boxCount', {
            rules: [{required: true, min: 1, message: '请输入至少五个字符的规则描述！'}], initialValue:9
          }]"
        />
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="柜名">
              <a-input v-decorator="['name', {rules: [{required: true, min: 1, message: '请输入至少五个字符的规则描述！'}], initialValue: (detailData)? detailData.name: ''}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="柜号">
              <a-input v-decorator="['id', {rules: [{required: true, min: 1, message: '请输入至少五个字符的规则描述！'}], initialValue: (detailData)? detailData.id: ''}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="电话">
              <a-input v-decorator="['tel', {rules: [{required: true, min: 5, message: '请输入至少五个字符的规则描述！'}], initialValue: (detailData)? detailData.tel: ''}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="说明">
              <a-input v-decorator="['summary', {rules: [{required: true, min: 5, message: '请输入至少五个字符的规则描述！'}], initialValue: (detailData)? detailData.summary: ''}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="开放时间">
              <a-input v-decorator="['openTime', {rules: [{required: true, min: 5, message: '请输入至少五个字符的规则描述！'}], initialValue: (detailData)? detailData.openTime: ''}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="关闭时间">
              <a-input v-decorator="['closeTime', {rules: [{required: true, min: 5, message: '请输入至少五个字符的规则描述！'}], initialValue: (detailData)? detailData.closeTime: ''}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <!-- <a-row>
          <a-col>
            <a-form-item label="地址" :labelCol="{span: 3}" :wrapperCol="{span: 21}">
              <a-auto-complete
                placeholder="input here"
                @search="searchMap"
                @select="searchChange"
                v-decorator="['place.address', {rules: [{required: true, min: 5, message: '请输入至少五个字符的规则描述！'}], trigger: 'change', initialValue: (detailData)? detailData.place.address: ''}]"
              >
                <template slot="dataSource">
                  <a-select-option v-for="(item, index) in mapResultDataSource" :key="index + ''">
                    {{ item.title }}
                  </a-select-option>
                </template>
              </a-auto-complete>
            </a-form-item>
          </a-col>
        </a-row> -->
        <custom-baidu-map @mapSelect="mapSelect" :detailData="detailData" />
        <!-- <baidu-map :center="mapCenter" :zoom="15" class="map" @ready="handlerMap" @click="mapClick">
          <bm-marker :position="{lng: mapCenter.lng, lat: mapCenter.lat}">
            <bm-label :content="(detailData)? detailData.place.address: ''" :labelStyle="{color: 'red'}" :offset="{height: 30}"/>
          </bm-marker>
        </baidu-map> -->
        <a-row :gutter="24" style="margin-top: 16px;">
          <a-col :span="12">
            <a-form-item label="经度">
              <a-input v-decorator="['place.coordinate.longitude', {initialValue: (detailData)? detailData.place.coordinate.longitude: ''}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="纬度">
              <a-input v-decorator="['place.coordinate.latitude', {initialValue: (detailData)? detailData.place.coordinate.latitude: ''}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="图片">
              <a-upload
                :headers="uploadHeader"
                :withCredentials="true"
                name="file"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                :customRequest="customRequest"
              >
                <img style="width:100%;" v-if="imageUrl" :src="imageUrl" alt="avatar" />
                <div v-else>
                  <a-icon :type="fileLoading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
              <!-- <a-input v-decorator="['photo', {rules: [{required: true, min: 5, message: '请输入至少五个字符的规则描述！'}], initialValue: (detailData)? detailData.photo: ''}]" /> -->
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { cabinetLists, saveCabinet, regCabinet } from '@/api/cabinet'
import { uploadImage } from '@/api/global'
import CustomBaiduMap from '@/views/baidu-map/CustomBaiduMap'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import storage from 'store'

export default {
  name: 'Detail',
  data () {
    this.formLayout = {
      labelCol: {
        span: 6
        // xs: { span: 24 },
        // sm: { span: 7 }
      },
      wrapperCol: {
        span: 18
        // xs: { span: 24 },
        // sm: { span: 13 }
      }
    }
    return {
      uploadHeader: {},
      fileLoading: false,
      imageUrl: '',
      modalStatus: 0, // 0 更新 1 添加
      result: [
        '1',
        '2'
      ],
      autoValue: '',
      mapResultDataSource: [
        {
          title: '',
          address: '',
          uid: ''
        }
      ],
      BMap: null,
      map: null,
      keyword: '浦东幼儿园',
      location: '中国',
      detailData: null,
      mapCenter: {
        lng: 0,
        lat: 0
      },
      form: this.$form.createForm(this, { id: 10000 })
    }
  },
  props: {
    title: {
      type: String,
      required: true,
      default: '详情'
    },
    update: {
      type: Boolean,
      required: true,
      default: true
    },
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  created () {
    this.uploadHeader = {
      AUTHORIZATION: 'Bearer ' + storage.get(ACCESS_TOKEN).toString()
    }
    if (this.update) {
      this.init()
    } else {
      this.detailData = {
        place: {
          address: '',
          coordinate: {
            longitude: 0,
            latitude: 0
          }
        }
      }
    }
  },
  components: {
    CustomBaiduMap
  },
  methods: {
    customRequest (options) {
      const { onSuccess, onError, file, onProgress } = options
      const reader = new FileReader()
      reader.readAsDataURL(file) // 读取图片文件
      reader.onload = (_file) => {
        const arr = _file.target.result.split(',')
        // const data = window.atob(arr[1])
        const mime = arr[0].match(/:(.*?);/)[1]
        // const ia = new Uint8Array(data.length)
        // for (var i = 0; i < data.length; i++) {
        //   ia[i] = data.charCodeAt(i)
        // }
        // const bloba = new Blob([ia], { type: mime })
        console.log(onProgress, onError, onSuccess)
        uploadImage(file, mime).then(res => {
          console.log(res)
          this.imageUrl = res.headers.location
        }).catch(e => {
          console.error(e)
        })
      }
    },
    // handleChange (info) {
    //   if (info.file.status === 'uploading') {
    //     this.fileLoading = true
    //     return
    //   }
    //   if (info.file.status === 'done') {
    //     // Get this url from response in real world.
    //     getBase64(info.file.originFileObj, imageUrl => {
    //       this.imageUrl = imageUrl
    //       this.fileLoading = false
    //     })
    //   }
    // },
    beforeUpload (file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
        return false
      }
      const reader = new FileReader()
      reader.readAsDataURL(file)
      return new Promise((resolve, reject) => {
        reader.onload = function () {
          resolve(reader.result)
        }
      })
      // const blob = new Blob([file], )
      // debugger
      // return false
      // return Promise.resolve()
      // const isLt2M = file.size / 1024 / 1024 < 2
      // if (!isLt2M) {
      //   this.$message.error('Image must smaller than 2MB!')
      // }
      // return isJpgOrPng && isLt2M
    },
    mapSelect ({ address, lng, lat }) {
      this.detailData.place.address = address
      this.detailData.place.coordinate.longitude = lng
      this.detailData.place.coordinate.latitude = lat
      this.form.setFieldsValue({
        'place.coordinate.longitude': lng,
        'place.coordinate.latitude': lat
      })
    },
    init () {
      cabinetLists({ id: this.model.id }).then(res => {
        this.detailData = res.data[0]
        this.imageUrl = this.detailData.photo
        this.form.setFieldsValue({
          'boxCount': this.detailData.boxes.length + ''
        })
        // this.detailData.boxCount = this.detailData.boxes.length
        this.mapCenter.lng = this.detailData.place.coordinate.longitude
        this.mapCenter.lat = this.detailData.place.coordinate.latitude
        console.log(res)
      }).catch(e => {
        console.error(e)
      })
    },
    modalOK () {
      console.log(this.model)
      this.form.validateFieldsAndScroll((error, values) => {
        values.place.address = this.detailData.place.address
        values.photo = this.imageUrl
        values.boxCount = 9
        if (!error && this.update) {
          saveCabinet(this.model.id, values).then(res => {
            console.log(res)
            this.$emit('ok')
          }).catch(e => {
            console.error(e)
          })
        } else {
          regCabinet(values.id, values).then(res => {
            console.log(res)
            this.$emit('ok')
          }).catch(e => {
            console.error(e)
          })
        }
      })
      // this.$form.submit
    },
    formSubmit () {
      console.log(saveCabinet)
    },
    cancelModal () {
      this.$emit('cancel')
      // () => { this.$emit('cancel') }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
